<template>
  <div class="collect h-100%">
    <div class="acea-row header">
      <div class="font18">全部宝贝({{tableData.total}})</div>
    </div>
    <!-- 筛选条件 -->
    <div class="filter-container mb-20px">
      <el-form :inline="true" label-width="70px" :model="where" class="filter-form">
        <el-form-item label="商品名称">
          <el-input
            v-model="where.keyword"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <!-- <el-form-item label="商户">
          <el-select
            v-model="where.merId"
            placeholder="请选择商户"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in merchantList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select
            v-model="where.brandId"
            placeholder="请选择品牌"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="商品分类">
          <el-cascader
            v-model="where.cateId"
            :options="categoryList"
            :props="cascaderProps"
            placeholder="请选择商品分类"
            clearable
            
            collapse-tags
            collapse-tags-tooltip
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select
            v-model="where.stock"
            placeholder="请选择库存状态"
            clearable
            style="width: 200px"
          >
            <el-option label="有货" :value="1" />
            <el-option label="无货" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">筛选</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleAllSelect">全选</el-button>
          <el-button type="primary" @click="handleRemove">批量移除选品库</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-loading="listLoading">
      <div v-if="tableData.total>0">
        <UserProductList ref="userProductListRef" :showBatch="false" :list="tableData.list" type="collect_products" @handleComplete="handleComplete"></UserProductList>
        <div class="acea-row row-middle mt-30px">
          <el-pagination background
                         layout="prev, pager, next"
                         :total="tableData.total"
                         :page-size="where.limit"
                         :current-page="where.page"  @update:current-page="pageChange" class="page-item" />
        </div>
      </div>
      <div v-else class="w-100%">
        <empty-page title="暂无选品呦~">
          <template v-slot:emptyImage>
            <img src="@/assets/images/wushoucang.png">
          </template>
        </empty-page>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getCollectProApi } from '~/server/userApi'
import { getMerCollectListApi } from '~/server/merchantApi'
import { productListBeforeApi, categoryTreeApi } from '~/server/goodsApi'
import { PageQuery } from '~/types/global'
import { reactive, ref } from 'vue'
import UserProductList from '~/components/userProductList.vue'
import { Search, Refresh } from '@element-plus/icons-vue'

const handleComplete = async () => {
  refresh()
}

const userProductListRef = ref()

/**
 * 筛选条件接口扩展
 */
interface CollectQuery extends PageQuery {
  keyword?: string
  merId?: number | string | null
  brandId?: number | string | null
  cateId?: (string | number)[] | string | null
  stock?: number | null
}

/**
 * 选品列表查询参数
 */
const where = reactive<CollectQuery>({
  page: 1,
  limit: 12,
  keyword: '',
  merId: null,
  brandId: null,
  cateId: null,
  stock: null,
})

/**
 * 商户列表
 */
const merchantList = ref<any[]>([])

/**
 * 品牌列表
 */
const brandList = ref<any[]>([])

/**
 * 分类列表
 */
const categoryList = ref<any[]>([])

/**
 * 级联选择器配置
 */
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'childList',
  multiple: true,
  checkStrictly: false, // 可以选择任意级别
  emitPath: false // 只返回选中节点的值，不返回完整路径
}

/**
 * 获取商户列表
 */
const getMerchantList = async () => {
  try {
    const res = await getMerCollectListApi({ page: 1, limit: 1000 })
    merchantList.value = res?.list || []
  } catch (error) {
    console.error('获取商户列表失败:', error)
  }
}

/**
 * 获取品牌和分类列表
 */
const getFilterOptions = async () => {
  try {
    const res = await productListBeforeApi({})
    brandList.value = res?.brandList || []
  } catch (error) {
    console.error('获取品牌列表失败:', error)
  }
  
  try {
    const categories = await categoryTreeApi()
    console.log(categories)
    // 保持树形结构用于级联选择器
    categoryList.value = categories || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

/**
 * 搜索
 */
const handleSearch = () => {
  where.page = 1
  refresh()
}

/**
 * 重置
 */
const handleReset = () => {
  where.page = 1
  where.keyword = ''
  where.merId = null
  where.brandId = null
  where.cateId = null
  where.stock = null
  refresh()
}

// 初始化筛选选项
await useAsyncData('filter-options', async () => {
  await Promise.all([
    getMerchantList(),
    getFilterOptions()
  ])
})
/**
 * 获取列表数据
 */
const {
  data: tableData,
  refresh,
  pending: listLoading,
} = await useAsyncData('collect-products', async () => {
  // 处理 cateId 参数
  const params = { ...where }
  if (params.cateId && Array.isArray(params.cateId)) {
    params.cateId = params.cateId.join(',')
  }
  return getCollectProApi(params)
}, {
  default: () => ({
    list: [],
    total: 0,
  }),
  // watch: [where]
})

/**
 * 分页数据
 */
const pageChange = (e: number) => {
  where.page = e
  refresh()
}

/**
 * 全选
 */
const handleAllSelect = () => {
  userProductListRef.value?.changeIsAllSelect()
}

/**
 * 批量移除选品库
 */
const handleRemove = () => {
  userProductListRef.value?.handleAllCancel()
}
</script>

<style scoped lang="scss">
.collect {
  .header {
    margin-bottom: 27px;
  }
  
  .filter-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    
    :deep(.el-form-item) {
      margin-bottom: 10px;
    }
    
    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #666;
    }
  }
}
</style>